<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<spring:eval expression="@propertyConfigurer.getProperty('url.cdn')" var="cdnUrl" />
<spring:eval expression="@propertyConfigurer.getProperty('build.version')" var="version" />
<!DOCTYPE html>
<html lang="${language}">
<head>
    <meta charset="UTF-8">
    <title><spring:message code="voj.teacher.new-contest.title" text="New Contest" /> | ${websiteName}</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="${description}">
    <meta name="author" content="Haozhe Xie">
    <!-- Icon -->
    <link href="${cdnUrl}/img/favicon.ico?v=${version}" rel="shortcut icon" type="image/x-icon">
    <!-- StyleSheets -->
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/component/layui/build/css/layui.css?v=${version}" />
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/css/bootstrap.min.css?v=${version}" />
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/css/bootstrap-responsive.min.css?v=${version}" />
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/css/flat-ui.min.css?v=${version}" />
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/css/font-awesome.min.css?v=${version}" />
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/css/teacher/style.css?v=${version}" />
    <link rel="stylesheet" type="text/css" href="${cdnUrl}/css/teacher/new-contest.css?v=${version}" />
    <!-- JavaScript -->
    <script type="text/javascript" src="${cdnUrl}/component/layui/build/layui.js"></script>
    <script type="text/javascript" src="${cdnUrl}/js/jquery-1.11.1.min.js?v=${version}"></script>
    <script type="text/javascript" src="${cdnUrl}/js/bootstrap.min.js?v=${version}"></script>
    <script type="text/javascript" src="${cdnUrl}/js/flat-ui.min.js?v=${version}"></script>
    <script type="text/javascript" src="${cdnUrl}/js/md5.min.js?v=${version}"></script>
    <script type="text/javascript" src="${cdnUrl}/js/pace.min.js?v=${version}"></script>
    <!--[if lte IE 9]>
        <script type="text/javascript" src="${cdnUrl}/js/jquery.placeholder.min.js?v=${version}"></script>
    <![endif]-->
    <!--[if lte IE 7]>
        <script type="text/javascript"> 
            window.location.href='<c:url value="/not-supported" />';
        </script>
    <![endif]-->
</head>
<body>
    <div id="wrapper">
        <!-- Sidebar -->
        <%@ include file="/WEB-INF/views/teacher/include/sidebar.jsp" %>
        <div id="container">
            <!-- Header -->
            <%@ include file="/WEB-INF/views/teacher/include/header.jsp" %>
            <!-- Content -->
            <div id="content">
                <h2 class="page-header"><i class="fa fa-file"></i> <spring:message code="voj.teacher.new-contest.new-contest" text="New Problem" /></h2>
                <form id="problem-form" onSubmit="onSubmit(); return false;">
                    <div class="row-fluid">
                        <div class="span8 noscrollbar">
                            <div class="alert alert-error hide"></div> <!-- .alert-error -->
                            <div class="control-group row-fluid">
                                <label for="contest-name"><spring:message code="voj.teacher.new-contest.contest-name" text="Problem Name" /></label>
                                <input id="contest-name" class="span12" type="text" maxlength="128" />
                            </div> <!-- .control-group -->
                            <layui-jh identify="starttime" labelname="<spring:message code="voj.teacher.new-contest.starttime" text="Problem Name" />"></layui-jh>
                            <layui-jh identify="endtime" labelname="<spring:message code="voj.teacher.new-contest.endtime" text="Problem Name" />"></layui-jh>
                            <div class="control-group row-fluid">
                                <label for="contest-mode"><spring:message code="voj.teacher.new-contest.contest-mode" text="Time Limit" /> (ms)</label>
                                <select id="contest-mode" class="span12"><option value="OI">OI</option><option value="ACM">ACM</option></select>
                            </div> <!-- .control-group -->
                            <div class="control-group row-fluid">
                                <label for="contest-note"><spring:message code="voj.teacher.new-contest.contest-note" text="Time Limit" /></label>
                                <textarea id="contest-note" row="4" class="span12"></textarea>
                            </div> <!-- .control-group -->
                            <div class="row-fluid">
                                <div class="span6" style="min-height: 20px;">
                                    <label style="margin-bottom: 0;"><spring:message code="voj.teacher.new-contest.contest-problems" text="Contest Problems" /></label>
                                </div> <!-- .span6 -->
                                <div class="span6 text-right" style="min-height: 20px;">
                                    <label style="margin-bottom: 0;">
                                        <a id="new-contest-problem" title='<spring:message code="voj.teacher.new-contest.new-contest-problem" text="New contest problem" />' href="javascript:void(0);">
                                            <i class="fa fa-plus-circle"></i>
                                        </a>
                                    </label>
                                </div> <!-- .span6 -->
                            </div> <!-- .row-fluid -->
                            <div class="row-fluid">
                                <div class="span12">
                                    <div id="contest-problems">
                                        <p id="no-contest-problem"><spring:message code="voj.teacher.new-contest.no-contest-problem" text="No Test Cases." /></p>
                                        <ul></ul>
                                    </div> <!-- #test-cases -->
                                </div> <!-- .span12 -->
                            </div> <!-- .row-fluid -->

                            <div class="row-fluid">
                                <div class="span6" style="min-height: 20px;">
                                    <label style="margin-bottom: 0;"><spring:message code="voj.teacher.new-contest.contest-classes" text="Contest Problems" /></label>
                                </div> <!-- .span6 -->
                                <div class="span6 text-right" style="min-height: 20px;">
                                    <label style="margin-bottom: 0;">
                                        <a id="new-contest-class" title='<spring:message code="voj.teacher.new-contest.new-contest-class" text="New contest class" />' href="javascript:void(0);">
                                            <i class="fa fa-plus-circle"></i>
                                        </a>
                                    </label>
                                </div> <!-- .span6 -->
                            </div> <!-- .row-fluid -->
                            <div class="row-fluid">
                                <div class="span12">
                                    <div id="contest-classes">
                                        <p id="no-contest-class"><spring:message code="voj.teacher.new-contest.no-contest-class" text="No Test Cases." /></p>
                                        <ul></ul>
                                    </div> <!-- #test-cases -->
                                </div> <!-- .span12 -->
                            </div> <!-- .row-fluid -->
                        </div>
                        <div class="span4">
                            <div class="section">
                                <div class="header">
                                    <h5><spring:message code="voj.teacher.new-contest.newcontest" text="Create Problem" /></h5>
                                </div> <!-- .header -->
                                <div class="body">
                                    <div class="row-fluid">
                                        <div class="span8">
                                            <spring:message code="voj.teacher.new-contest.is-public" text="Public to Users?" />
                                            <i class="fa fa-info-circle" title="<spring:message code="voj.teacher.new-contest.is-public-info" text="Info" />"></i>
                                        </div> <!--- .span8 -->
                                        <div class="span4 text-right">
                                            <input id="contest-is-public" type="checkbox" data-toggle="switch" checked="checked" />
                                        </div> <!-- .span4 -->
                                    </div> <!-- .row-fluid -->
                                    <div class="row-fluid">
                                        <div class="span8">
                                            <spring:message code="voj.teacher.new-contest.is-edit-public" text="Test Case Exactly Match" />
                                            <i class="fa fa-info-circle" title="<spring:message code="voj.teacher.new-contest.is-edit-public-info" text="Info" />"></i>
                                        </div> <!--- .span8 -->
                                        <div class="span4 text-right">
                                            <input id="contest-is-edit-public" type="checkbox" data-toggle="switch" />
                                        </div> <!-- .span4 -->
                                    </div> <!-- .row-fluid -->
                                </div> <!-- .body -->
                                <div class="footer text-right">
                                    <button class="btn btn-primary" type="submit"><spring:message code="voj.teacher.new-contest.create-contest" text="Publish" /></button>
                                </div> <!-- .footer -->
                            </div> <!-- .section -->
                        </div> <!-- .span4 -->
                    </div> <!-- .row-fluid -->
                </form>
            </div> <!-- #content -->
        </div> <!-- #container -->
    </div> <!-- #wrapper -->
    <!-- Java Script -->
    <!-- Placed at the end of the document so the pages load faster -->
    <%@ include file="/WEB-INF/views/teacher/include/footer-script.jsp" %>
    <script type="text/javascript">
        $(function() {
            $('.tagsinput').tagsInput();
            $('[data-toggle=switch]').wrap('<div class="switch" />').parent().bootstrapSwitch();
        });
    </script>
    <!-- New Problem -->
    <script type="text/javascript">
        $('#new-contest-problem').click(function() {
            var problemId = $('li.contest-problem', '#contest-problems').length; 
            
            $('#no-contest-problem').addClass('hide');
            $('#contest-problems > ul').append(getContestProblemContainer(problemId));
        });
    </script>
    <script type="text/javascript">
        function getContestProblemContainer(problemId) {
            var containerTemplate = `<li class="contest-problem">
                                        <div class="header">
                                            <h5><spring:message code="voj.teacher.new-contest.contest-problem" text="Contest Problem" /> #%s</h5>
                                            <ul class="inline">
                                                <li><a href="javascript:void(0);"><i class="fa fa-edit"></i></a></li>
                                                <li><a href="javascript:void(0);"><i class="fa fa-trash"></i></a></li>
                                            </ul>
                                        </div> <!-- .header -->
                                        <div class="body">
                                            <div class="row-fluid">
                                                <div class="span3">
                                                    <label><spring:message code="voj.teacher.common.problem-id" text="Problem Id" /></label>
                                                </div> <!-- .span4 -->
                                                <div class="span9">
                                                    <input id="p_\${problemId}" class="problem-id span12" onblur="prepareP(event,\${problemId})" type="text">
                                                </div> <!-- .span8 -->
                                            </div> <!-- .row-fluid -->
                                            <div class="row-fluid">
                                                <div class="span3">
                                                    <label><spring:message code="voj.teacher.common.problem-pre" text="Problem Preview" /></label>
                                                </div> <!-- .span4 -->
                                                <div id="pp_\${problemId}" class="span9" style="border: rgb(216, 222, 227) solid 1px;border-radius: 6px;padding: 5px 8px;margin-bottom: 10px;">
                                                </div> <!-- .span8 -->
                                            </div> <!-- .row-fluid -->
                                        </div>`;
            return containerTemplate.format(problemId);
        }
        function prepareP(event, id) {
            $.ajax({
                type: 'GET',
                url: `<c:url value="/teacher/problem/\${event.target.value}" />`,
                success: function(result){
                    if(result.result == "success") {
                        $(`#pp_\${id}`).html(`<p style="text-overflow: ellipsis;overflow: hidden;white-space: nowrap;margin-bottom: 0;">\${result.problemName}<br>
                            <span style="float: right;"><i class="fa fa-clock-o" aria-hidden="true"></i>&nbsp;\${result.problemTimeLimit}ms |&nbsp;<i class="fa fa-archive" aria-hidden="true"></i>&nbsp;\${result.problemMemoryLimit}k
                            </span>
                        </p>`);
                    } else {
                        $('#pp_0').html(`<p style="text-overflow: ellipsis;overflow: hidden;white-space: nowrap;margin-bottom: 0;">No Problem Found
                        </p>`);
                    }
                    // return processCreateProblemResult(result);
                }
            });
        }
    </script>
    <script type="text/javascript">
        $('#contest-problems').on('click', 'i.fa-edit', function() {
            var testCaseContainer = $(this).parent().parent().parent().parent().parent(),
                isBodyUnfolded      = $('.body', $(testCaseContainer)).is(':visible');

            if ( isBodyUnfolded ) {
                $('.body', $(testCaseContainer)).addClass('hide');
            } else {
                $('.body', $(testCaseContainer)).removeClass('hide');
            }
        });
    </script>
    <script type="text/javascript">
        $('#contest-problems').on('click', 'i.fa-trash', function() {
            var testCaseContainer = $(this).parent().parent().parent().parent().parent(),
                testCases         = $('li.contest-problem', '#contest-problems').length,
                testCaseName      = '<spring:message code="voj.teacher.new-contest.contest-problem" text="Contest Problem" /> #%s';

            $(testCaseContainer).remove();
            $('li.contest-problem', '#contest-problems').each(function(index) {
                $('h5', this).html(testCaseName.format(index));
            });

            if ( testCases == 1 ) {
                $('#no-contest-problem').removeClass('hide');
            }
        });
    </script>
    <!-- New Class -->
    <script type="text/javascript">
        var classes = [];
        $.ajax({
            type: 'GET',
            url: `<c:url value="/teacher/get-all-classes.action" />`,
            success: function(result){
                classes = result;
            }
        });
        $('#new-contest-class').click(function() {
            var classId = $('li.contest-class', '#contest-classes').length;
            $('#no-contest-class').addClass('hide');
            $('#contest-classes > ul').append(getContestClassContainer(classId));
        });
    </script>
    <script type="text/javascript">
        function getContestClassContainer(classId) {
            var containerTemplate = `<li class="contest-class">
                                        <div class="header">
                                            <h5><spring:message code="voj.teacher.new-contest.contest-class" text="Contest Class" /> #%s</h5>
                                            <ul class="inline">
                                                <li><a href="javascript:void(0);"><i class="fa fa-edit"></i></a></li>
                                                <li><a href="javascript:void(0);"><i class="fa fa-trash"></i></a></li>
                                            </ul>
                                        </div> <!-- .header -->
                                        <div class="body">
                                            <div class="row-fluid">
                                                <div class="span3">
                                                    <label><spring:message code="voj.teacher.common.class-id" text="Class Id" /></label>
                                                </div> <!-- .span4 -->
                                                <div class="span9">
                                                    <select id="c_\${classId}" class="class-id span12" onchange="prepareC(event,\${classId})">
                                                        <option value="0"></option>
                                                        \${classes.map(item=>`<option value="\${item.cid}">\${item.classname}</option>`).join()}
                                                    </select>
                                                </div> <!-- .span8 -->
                                            </div> <!-- .row-fluid -->
                                            <div class="row-fluid">
                                                <div class="span3">
                                                    <label><spring:message code="voj.teacher.common.class-pre" text="Class Preview" /></label>
                                                </div> <!-- .span4 -->
                                                <div id="pc_\${classId}" class="span9" style="border: rgb(216, 222, 227) solid 1px;border-radius: 6px;padding: 5px 8px;margin-bottom: 10px;">
                                                </div> <!-- .span8 -->
                                            </div> <!-- .row-fluid -->
                                        </div>`;

            return containerTemplate.format(classId);
        }
        function prepareC(event, id) {
            for(let i = 0; i<classes.length; i++){
                if(event.target.value == classes[i].cid){
                    $(`#pc_\${id}`).html(`<p style="text-overflow: ellipsis;overflow: hidden;white-space: nowrap;margin-bottom: 0;">\${classes[i].classname}<br>
                        <span style="float: right;"><i class="fa fa-book" aria-hidden="true"></i><span style="font-size: 12px">&nbsp;\${classes[i].lessonname} |&nbsp;</span><i class="fa fa-users" aria-hidden="true"></i>&nbsp;\${classes[i].studentcount}
                        </span>
                    </p>`);
                }
            }
        }
    </script>
    <script type="text/javascript">
        $('#contest-classes').on('click', 'i.fa-edit', function() {
            var testCaseContainer = $(this).parent().parent().parent().parent().parent(),
                isBodyUnfolded      = $('.body', $(testCaseContainer)).is(':visible');

            if ( isBodyUnfolded ) {
                $('.body', $(testCaseContainer)).addClass('hide');
            } else {
                $('.body', $(testCaseContainer)).removeClass('hide');
            }
        });
    </script>
    <script type="text/javascript">
        $('#contest-classes').on('click', 'i.fa-trash', function() {
            var testCaseContainer = $(this).parent().parent().parent().parent().parent(),
                testCases         = $('li.contest-class', '#contest-classes').length,
                testCaseName      = '<spring:message code="voj.teacher.new-contest.contest-class" text="Contest Problem" /> #%s';

            $(testCaseContainer).remove();
            $('li.contest-class', '#contest-classes').each(function(index) {
                $('h5', this).html(testCaseName.format(index));
            });

            if ( testCases == 1 ) {
                $('#no-contest-class').removeClass('hide');
            }
        });
    </script>

    <script type="text/javascript">
        $('label.checkbox.parent-category').click(function() {
            var currentControl = $(this);
            // Fix the bug for Checkbox in FlatUI 
            setTimeout(function() {
                var isChecked = $(currentControl).hasClass('checked');

                if ( !isChecked ) {
                    $('label.checkbox.child-category', $(currentControl).parent()).removeClass('checked');
                }
            }, 50);
        });
    </script>
    <script type="text/javascript">
        $('label.checkbox.child-category').click(function() {
            var currentControl = $(this);
            // Fix the bug for Checkbox in FlatUI 
            setTimeout(function() {
                var isChecked = $(currentControl).hasClass('checked');

                if ( isChecked ) {
                    $('label.checkbox.parent-category', $(currentControl).parent().parent().parent()).addClass('checked');
                }
            }, 50);
        });
    </script>
    <script type="text/javascript">
        function getProblems() {
            problems = []
            $('li.contest-problem').each(function() {
                var problem  = $('.problem-id', $(this)).val();
                problems.push(problem);
            });
            return JSON.stringify(problems); 
        }
        function getClasses() {
            classes = []
            $('li.contest-class').each(function() {
                var problem  = $('.class-id', $(this)).val();
                classes.push(problem);
            });
            return JSON.stringify(classes); 
        }
    </script>
    <script type="text/javascript">
        function onSubmit() {
            var contestName         = $('#contest-name').val(),
                starttime           = $('#starttime').val(),
                endtime             = $('#endtime').val(),
                contestMode         = $('#contest-mode').val(),
                contestNote         = $('#contest-note').val(),
                contestPublic       = document.querySelector('#contest-is-public').checked,
                contestEditPublic   = document.querySelector('#contest-is-edit-public').checked,
                problems            = getProblems(),
                classes             = getClasses();

            $('.alert-success', '#problem-form').addClass('hide');
            $('.alert-error', '#problem-form').addClass('hide');
            $('button[type=submit]', '#problem-form').attr('disabled', 'disabled');
            $('button[type=submit]', '#problem-form').html('<spring:message code="voj.common.please-wait" text="Please wait..." />');

            return createContest(contestName, starttime, endtime, contestMode, contestNote, contestPublic, contestEditPublic, problems, classes);
        }
    </script>
    <script type="text/javascript">
        function createContest(contestName, starttime, endtime, contestMode, contestNote, contestPublic, contestEditPublic, problems, classes) {
            var postData = {
                contestName, starttime, endtime, contestMode, contestNote, contestPublic, contestEditPublic, problems, classes
            };

            $.ajax({
                type: 'POST',
                url: '<c:url value="/teacher/createContest.action" />',
                data: postData,
                dataType: 'JSON',
                success: function(result){
                    // console.log("success");
                    return processCreateContestResult(result);
                }
            });
        }
    </script>
    <script type="text/javascript">
        function processCreateContestResult(result) {
            if ( result['isSuccessful'] ) {
                var contestId = result['contestId'];
                window.location.href = '<c:url value="/teacher/edit-contest/" />' + contestId;
            } else {
                var errorMessage  = '';
                if ( result['isContestNameEmpty'] ) {
                    errorMessage += '<spring:message code="voj.administration.new-problem.problem-name-empty" text="You can&acute;t leave Problem Name empty." /><br>';
                } else if ( !result['isContestNameLegal'] ) {
                    errorMessage += '<spring:message code="voj.administration.new-problem.problem-name-illegal" text="The length of Problem Name CANNOT exceed 128 characters." /><br>';
                }
                if ( !result['isTimeLimitLegal'] ) {
                    errorMessage += '<spring:message code="voj.administration.new-problem.time-limit-illegal" text="The Time Limit should be an integer greater than 0." /><br>';
                } 
                if ( !result['isMemoryLimitLegal'] ) {
                    errorMessage += '<spring:message code="voj.administration.new-problem.memory-limit-illegal" text="The Memory Limit should be an integer greater than 0." /><br>';
                } 
                if ( result['isDescriptionEmpty'] ) {
                    errorMessage += '<spring:message code="voj.administration.new-problem.description-empty" text="You can&acute;t leave Description empty." /><br>';
                }
                if ( result['isInputFormatEmpty'] ) {
                    errorMessage += '<spring:message code="voj.administration.new-problem.input-format-empty" text="You can&acute;t leave Input Format empty." /><br>';
                } 
                if ( result['isOutputFormatEmpty'] ) {
                    errorMessage += '<spring:message code="voj.administration.new-problem.output-format-empty" text="You can&acute;t leave Output Format empty." /><br>';
                } 
                if ( result['isInputSampleEmpty'] ) {
                    errorMessage += '<spring:message code="voj.administration.new-problem.input-sample-empty" text="You can&acute;t leave Input Sample empty." /><br>';
                } 
                if ( result['isOutputSampleEmpty'] ) {
                    errorMessage += '<spring:message code="voj.administration.new-problem.output-sample-empty" text="You can&acute;t leave Output Sample empty." /><br>';
                } 

                $('.alert-error', '#problem-form').html(errorMessage);
                $('.alert-error', '#problem-form').removeClass('hide');
            }
            $('button[type=submit]', '#problem-form').removeAttr('disabled');
            $('button[type=submit]', '#problem-form').html('<spring:message code="voj.administration.new-problem.publish-problem" text="Publish" />');
        }
    </script>
</body>
<%@ include file="/WEB-INF/views/include/script.jsp" %>
</html>